package com.pl.service.impl;

import com.alibaba.excel.EasyExcel;
import com.pl.entity.Order;
import com.pl.entity.Part;
import com.pl.dao.PartDao;
import com.pl.lister.OrderLister;
import com.pl.lister.PartLister;
import com.pl.service.PartService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * (Part)表服务实现类
 *
 * @author makejava
 * @since 2024-04-30 15:17:53
 */
@Service("partService")
public class PartServiceImpl implements PartService {
    @Autowired
    private PartDao partDao;

    /**
     * 通过ID查询单条数据
     *
     * @param pid 主键
     * @return 实例对象
     */
    @Override
    public Part queryById(Integer pid) {
        return this.partDao.queryById(pid);
    }

    /**
     * 分页查询
     *
     * @return 查询结果
     */
    @Override
    public List<Part> queryByPage(Map<String, Object> map) {
        return this.partDao.queryAllByLimit(map);
    }

    /**
     * 新增数据
     *
     * @param part 实例对象
     * @return 实例对象
     */
    @Override
    public Part insert(Part part) {
        this.partDao.insert(part);
        return part;
    }

    /**
     * 修改数据
     *
     * @param part 实例对象
     * @return 实例对象
     */
    @Override
    public Part update(Part part) {
        this.partDao.update(part);
        return this.queryById(part.getPid());
    }

    /**
     * 通过主键删除数据
     *
     * @param pid 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer pid) {
        return this.partDao.deleteById(pid) > 0;
    }

    @Override
    public boolean deleteBatch(List<Integer> list) {
        int i = partDao.deleteBatch(list);
        if (i > 0) {
            return true;
        }
        return false;    }

    @Override
    public boolean finAll() {
        List<Part> orders = partDao.finAll();
        if (orders != null) {
            return true;
        }
        return false;    }

    @Override
    public String importOrderFile(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), Part.class, new PartLister(this)).sheet("零件信息").doReadSync();
            return "import_success";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "fail";    }

    @Override
    public boolean inserts(List<Part> partList) {
        int num = partDao.insertBatch(partList);
        if (num > 0) {
            return true;
        }
        return false;
    }

    @Override
    public void exportOrderFile(HttpServletResponse response) {
        List<Part> partList = partDao.finAll();
        try {
            EasyExcel.write(response.getOutputStream(), Part.class).sheet("零件信息").doWrite(partList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
